package com.rtx.wms.std.handler.qc.down;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.rtx.common.HttpServletRequestUtil;
import com.rtx.model.dto.edi.EdiInnerRequestDTO;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.ctclass.ClassHolder;
import com.rtx.wms.std.qc.bean.ApiQc;
import com.rtx.wms.std.qc.bean.ApiQcDetail;
import com.rtx.wms.std.qc.service.ApiQcService;
import com.rtx.wms.std.validation.qc.QcCheck;

/**
 * 格瑞普 qc质检结果下发
 * @author Administrator
 *
 */
@SuppressWarnings("all")
@Component
public class QcDownHadler {

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	QcCheck qcCheck;
	
	@Autowired
	ApiQcService apiQcService;
	
 
	public void createQcResult(HttpServletRequest request) {
    	ApiQc qc = null;
    	
      	String requestStr = HttpServletRequestUtil.getHttpBody(request);
		EdiInnerRequestDTO dto = JSON.parseObject(requestStr, EdiInnerRequestDTO.class);
		request.setAttribute("config", dto.getConfig());
    	
		//目标json转换成po对象
		qc = targetJsonConvertApipo(dto.getTagetjson(),dto);
		qc.setEdiflag("P");
    	
    	//常规校验
		qcCheck.checkEnterpriseConfig(WmsConstant.ENTERPRISE,qc);
    	
		//插入qc
		apiQcService.insertApiQcAndDetail("ris_edi", qc);
	}
	
	
    /**
     * 目标json转换成po对象
     * @throws InvocationTargetException 
     * @throws Exception 
     * 
     */
    public ApiQc targetJsonConvertApipo(String targetJson,EdiInnerRequestDTO dto){
    	ApiQc head = null;
    	try {
    		String apiid =  dto.getConfig().getTargetapiid();
        	Map<String,Class> map = ClassHolder.apiconfigClassMap.get(apiid);
    		if(map!= null && map.get("main")!=null) {
    			Class headclass = map.get("main");
            	Class subclass =map.get("sub");
            	head = (ApiQc) JSON.parseObject(targetJson,headclass);
            	List<ApiQcDetail> sub = JSON.parseArray(JSON.parseObject(targetJson).getString("details") ,subclass);
            	head.setDetails(sub);
    		}else {
    			head = JSON.parseObject(dto.getTagetjson(), ApiQc.class);
    		}

		} catch (Exception e) {
			logger.error("目标json转换成po对象异常-",e);
		}

    	return head;
    }
	
}
